package com.sndn.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;

public class InnerHorizontalScrollView extends HorizontalScrollView {

    public InnerHorizontalScrollView(Context context) {
        super(context);
    }

    public InnerHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public InnerHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private int getMaxX() {
        int maxX = -1;
        if (getChildCount() > 0 && maxX < 0) {
            maxX = getChildAt(0).getMeasuredWidth() - getWidth();
        }
        return maxX;
    }

    //在Y轴上可以滑动的最大距离 = 总长度 - 当前展示区域长度
    private int mMaxX = -1;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //获取父控件的父控件,对应外层ScrollView的节点
                getParent().getParent().requestDisallowInterceptTouchEvent(true);
                mMaxX = getMaxX();
                break;
            case MotionEvent.ACTION_MOVE:
                //滑到头 或者 滑到底部,请求外部的ScrollView拦截事件
                if (getScrollX() <= 0 || getScrollX() >= mMaxX) {
                    //拦截
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                getParent().getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
}